package com.sjyl.kaoshitong.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * Created by ChangerLow on 14-4-14.
 */
public class Utility {
    private static final String TAG = "Utility";
    private static TelephonyManager phoneManager;
    public static String accessKey = "ZoIYhan-puwT5etoKbLv_7mrs9bMDxIYah6KLkjZ";
    public static String secretKey = "-qL4KqIx2luFkpANvcCcvuCOEQy2gO2s3sySSBke";
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    public static String PUBLISHER_ID="a15354927837b55";
    public static String DEVICE_ID="8B4A382F215AFBC199EC6817535CC299";
    private static String funBaseUrl= "http://www.kst985.com:8080/identManager/";
    private static String kstBaseUrl = "http://www.kst985.com:8080/kst/";
    private static String downBaseUrl="http://www.kst985.com:8080/kst/down";
    private static String questionBaseUrl = "http://www.kst985.com:8080/kst/upQuestion/";
    private static String faqUrl = "http://www.kst985.com:8080/kst/QAPage.html";


    public static final String SHARESDK_APP_KEY = "299778622c4c";
    public static final String SHARESDK_APP_SECRET ="7782ac8b6b06ffe8bd2bd52a7151b717";

    public static final String RESPONSE_METHOD = "method";
    public static final String RESPONSE_CONTENT = "content";
    public static final String RESPONSE_ERRCODE = "errcode";
    protected static final String ACTION_LOGIN = "com.baidu.pushdemo.action.LOGIN";
    public static final String ACTION_MESSAGE = "com.baiud.pushdemo.action.MESSAGE";
    public static final String ACTION_RESPONSE = "bccsclient.action.RESPONSE";
    public static final String ACTION_SHOW_MESSAGE = "bccsclient.action.SHOW_MESSAGE";
    protected static final String EXTRA_ACCESS_TOKEN = "access_token";
    public static final String EXTRA_MESSAGE = "message";
    public static final String UNION_PAY_MODE = "00";
    public static final int PHOTO_REQUEST_GALLERY = 1;
    public static final int PHOTO_REQUEST_CAMERA = 2;
    public static final int PHOTO_REQUEST_CROP = 3;
    public static final int MAX_QUESTION_TITLE_LENGTH = 30;
    public static final int MAX_QUESTION_CONTENT_LEGNTH = 100;
    public static final int MAX_CROP_IMAGE_LIMIT = 1048576;
    public static int DISK_IMAGECACHE_SIZE = 1024*1024*10;
    public static Bitmap.CompressFormat DISK_IMAGECACHE_COMPRESS_FORMAT = Bitmap.CompressFormat.JPEG;
    public static int DISK_IMAGECACHE_QUALITY = 100;  //PNG is lossless so quality is ignored but must be provided
    public static String[] statusTextArray = {"未审核", "审核通过", "审核未通过", "处理完毕"};
    public static enum TAB_TYPE {
        DOCUMENT, QB, QA
    }


    public static String logStringCache = "";


    private static long DAY_INTERVAL = 1000*60*60*24;

    public Utility(){

    }


    public static String getDeviceId(Context context){
        phoneManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return phoneManager.getDeviceId();
    }

    public static String getFunBaseUlr(){
        return funBaseUrl;
    }

    public static String getKstBaseUrl() {
        return kstBaseUrl;
    }

    public static String getDownBaseUrl(){
        return downBaseUrl;
    }

    public static String getQuestionBaseUrl() {
        return questionBaseUrl;
    }

    public static String getFaqUrl(){ return  faqUrl;}



    public static long getFirstTime(){
        long firstTime = SystemClock.elapsedRealtime(); // 开机之后到现在的运行时间(包括睡眠时间)
        long systemTime = System.currentTimeMillis();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        // 这里时区需要设置一下，不然会有8个小时的时间差
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 选择的定时时间
        long selectTime = calendar.getTimeInMillis();
        // 如果当前时间大于设置的时间，那么就从第二天的设定时间开始
        if(systemTime > selectTime) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            selectTime = calendar.getTimeInMillis();
        }
        // 计算现在时间到设定时间的时间差
        long time = selectTime - systemTime;
        firstTime += time;

        return firstTime;
    }

    public static long getDayInterval(){
        return DAY_INTERVAL;
    }


    public static int getVersionCode(Context context) {
        int versionCode = 1;
        try{
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            versionCode = 1;
        }
        return versionCode;
    }




    // 获取ApiKey
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (PackageManager.NameNotFoundException e) {

        }
        return apiKey;
    }

    public static boolean checkSDcardExist(){
        Boolean isExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if(isExist)
            return true;
        else
            return false;
    }


    // 用share preference来实现是否绑定的开关。在ionBind且成功时设置true，unBind且成功时设置false
    public static boolean hasBind(Context context) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        String flag = sp.getString("bind_flag", "");
        if ("ok".equalsIgnoreCase(flag)) {
            return true;
        }
        return false;
    }

    public static void setBind(Context context, boolean flag) {
        String flagStr = "not";
        if (flag) {
            flagStr = "ok";
        }
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("bind_flag", flagStr);
        editor.commit();
    }


    public static String getRootDirectoryPath(){
        String path = "";
        if(checkSDcardExist()) {
            path = Environment.getExternalStorageDirectory().getPath() + "/.kaoshitong/";
        }
        return path;
    }

    public static String getFilePath(String userId, String src) {
        String path = null;
        if (src == null || src.equals(""))
            return path;
        if (userId == null || userId.equals(""))
            return path;

        String sdPath = Environment.getExternalStorageDirectory().getPath() + "/.kaoshitong/";
        src = src.replace("\\", "/");

        File dir = new File(sdPath + userId + "/");
        if (!dir.exists())
            dir.mkdirs();
        path = sdPath + userId + "/" + src;
        Log.d(TAG, path);
        return path;

    }


    public static String getVersionName(Context context)
    {

        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        String version="";
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if(packInfo == null){
            return "";
        }
        version = packInfo.versionName;
        return version;
    }

    public static int dp2Px(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }

    public static int dp2px(Context context, int dp) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        DisplayMetrics displaymetrics = new DisplayMetrics();
        display.getMetrics(displaymetrics);

        return (int) (dp * displaymetrics.density + 0.5f);
    }

    public static int px2dp(Context context, int px) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        DisplayMetrics displaymetrics = new DisplayMetrics();
        display.getMetrics(displaymetrics);

        return (int) (px / displaymetrics.density + 0.5f);
    }

}
